package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.mapper.TravelCommendMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TravelCommendServiceImpl implements ITravelCommendService {
    @Autowired
    private TravelCommendMapper travelCommendMapper;

    public List<Map<String, Object>> listCommends(Integer type) {
        Date begin = null;
        Date end = DateUtil.getEndDate(new Date());
        if (type == TravelCommend.TYPE_WEEK) { //需要设置7天前开始
            begin = DateUtil.getSevenDaysAgo(end);
        } else if (type == TravelCommend.TYPE_MONTH) { //需要设置上一个月开始
            begin = DateUtil.getAMonthAgo(end);
        }
        return travelCommendMapper.selectForApp(type, begin, end);
    }

    public void saveOrUpdate(TravelCommend entity) {
        if (entity.getId() == null) {
            //处理当前是保存攻略推荐,删除之前的攻略推荐
            if (entity.getType() == TravelCommend.TYPE_STRATEGY) {
                travelCommendMapper.deleteOldStrategyCommend();
            }
            travelCommendMapper.insert(entity);
        } else {
            //当前不是推荐推荐,并且要改为攻略推荐
            if (checkOperation(entity)) {
                travelCommendMapper.deleteOldStrategyCommend();
            }
            travelCommendMapper.updateByPrimaryKey(entity);
        }
    }

    public PageInfo<TravelCommend> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<TravelCommend> list = travelCommendMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    ///检查当前不是推荐推荐,并且要改为攻略推荐操作
    private boolean checkOperation(TravelCommend entity) {
        return entity.getType() == TravelCommend.TYPE_STRATEGY &&
               travelCommendMapper.selectTypeById(entity.getId()) != TravelCommend.TYPE_STRATEGY;
    }
}
